package com.woniuxy.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.media.jfxmedia.logging.Logger;
import com.woniuxy.entity.*;
import com.woniuxy.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import static java.lang.Integer.parseInt;
@Slf4j
@Controller
@RequestMapping("order")
public class OrdersController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private CartService cartService;

    @Autowired
    private ReviewService reviewService;

    @PostMapping("add")
    /* @Transactional(rollbackFor = Exception.class)*/
    public String list(HttpSession session, Model model, HttpServletRequest request) {
        Order order = new Order();
        //获取用户ID
        User user = (User) session.getAttribute("user");
        //获取相应的数据
        //获取所选的地址ID
        String addrid = request.getParameter("rdColor");
        System.out.println(addrid);
        Address address = addressService.getByIdAddr(Integer.parseInt(addrid));
        //获取留言
        String msg = request.getParameter("msg");
        //获取支付方式
        String pay = request.getParameter("pay");
        System.out.println(pay);
        //获取购物车ID     查找相对应的商品
        String[] cartids = request.getParameterValues("cartids");
        List<Cart> dishs = new ArrayList<>();
        for (String cartid : cartids) {
            dishs.add(cartService.getByDish(user.getId(), parseInt(cartid)));
        }
        //计算总价
        BigDecimal zprice = new BigDecimal("0.00");
        for (Cart dish : dishs) {
            System.out.println(dish.getNums() + "+++++++++" + "++++++++++" + dish.getDish().getPrice());
            BigDecimal num = new BigDecimal(dish.getNums() + "");
            BigDecimal price = new BigDecimal(dish.getDish().getPrice() + "");
            BigDecimal z = num.multiply(price);
            System.out.println(z);
            zprice = zprice.add(z);
            System.out.println(zprice);
        }
        //生成随机订单编号
        String times = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDateTime.now());
        int a = (int) (Math.random() * (9999 - 1000 + 1)) + 1000;
        order.setOrderNum("gfr" + times + a);
        order.setUserId(user.getId());
        order.setAddress(address.getProvince() + "" + address.getCity() + "" + address.getDistrict());
        order.setOrderTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
        order.setReciever(address.getPerson());
        order.setStatus("1");
        order.setOrderMsg(msg);
        order.setPhoneNum(address.getPhone());
        order.setPayWay(pay);
        order.setPrice(zprice);
        /*orderService.save(order);*/

        //添加订单详情
        OrderItem orderItem = new OrderItem();
        List<OrderItem> details = new ArrayList<>();
        for (Cart dish : dishs) {
            orderItem.setOrderId(order.getId());
            System.out.println(order.getId());
            orderItem.setDishId(dish.getDishId());
            orderItem.setDishNum(dish.getNums());
            orderItem.setPrice(dish.getDish().getPrice());
            details.add(orderItem);
            /*orderItemService.adds(orderItem);*/
        }
        orderService.add(order,details);
        model.addAttribute("number", "gfr" + times + a);
        model.addAttribute("money", zprice);
        return "order_verify";
    }

    //支付成功修改订单状态
    @PostMapping("update/{number}")
    @ResponseBody
    public ResponseEntity update(@PathVariable String number, HttpSession session) {
        User user = (User) session.getAttribute("user");
        System.out.println(number);
        orderService.update(number, user.getId(), 2);
        return ResponseEntity.SUCCESS;
    }

    /**
     * 我的订单    分页查询
     */
    @GetMapping("list")
    public String list(HttpSession session, Model model, Integer current) {
        User user = (User) session.getAttribute("user");
        Order order = new Order();
        order.setUserId(user.getId());
        if (current == null || current == 0) {
            current = 1;
        }
        QueryWrapper<Order> queryWrapper=new QueryWrapper<>();
        if(user.getId()!=0){
            queryWrapper.eq("user_id",user.getId());
        }
        Page<Order> page= new Page<>(current,2);
        model.addAttribute("page",orderService.page(page,queryWrapper));

        return "ucenter/user_orderlist";
    }

    /**
     * 个人中心取消订单
     * @param id
     * @return
     */
    @GetMapping("del")
    public String del(int id){
        Order order = new Order();
        order.setId(id);
        order.setStatus("8");
        orderService.updateById(order);
        return "redirect:/order/list";
    }

    /**
     * 个人中心订单支付
     * @param id
     * @return
     */
    @GetMapping("pay")
    public String pay(int id){
        Order order = new Order();
        order.setId(id);
        order.setStatus("2");
        orderService.updateById(order);
        return "redirect:/order/list";
    }

    @PostMapping("review")
    public String review(String score,String desc,String orderId){

        //已经付款的状态为2，1待付款


        Review review1=reviewService.getByOrderId(Integer.parseInt(orderId));
        if(review1!=null){
            return "redirect:/order/list?current=0";
        }
        Review review = new Review();
        review.setComment(desc);
        review.setOrderId(Integer.parseInt(orderId));
        review.setScore(Integer.parseInt(score));
        //保存评价
        reviewService.save(review);
        //更新order的评价状态为已经评价
        //将状态改为7

        orderService.update1(Integer.parseInt(orderId),"1",7);

//        log.debug("score:{},desc:{},orderId:{}",score,desc,orderId);

        return "redirect:/order/list?current=0";
    }
    @GetMapping("showReview")
    @ResponseBody
    public ResponseEntity showReview(Integer orderId){
//        Order order = orderService.getById(orderId);
        Review review=reviewService.getByOrderId(orderId);
        ResponseEntity<Review> responseEntity = new ResponseEntity<>(review);
        return responseEntity;
    }

}
